//
//  HomeViewController.m
//  QuickCure1
//
//  Created by maoge on 16/10/30.
//  Copyright © 2016年 maoge. All rights reserved.
//

#import "HomeViewController.h"
#import "WGWheathCollectionViewCell.h"
#import "WGCycleCollectionViewCell.h"
#import "NetWorkTool.h"
#import "HMHomeFunctionModel.h"
#import "ZWHomeFunctionCell.h"
#import "Weather.h"
#import "ViewController.h"
#import "WGCityTableViewController.h"
#import "WGCityModel.h"
#import "WGMingYiCollectionViewCell.h"
#import "WGDeseaseController.h"
#import "BaseNavController.h"
#import "WGTestHeartRateViewController.h"
#import "WGComplicationModel.h"
#import "LoginViewController.h"
#import "WGALertLoginView.h"
#import "BJXieHeViewController.h"
#import "WGScanViewController.h"



static NSString *testCellId = @"cell";
static NSString *wheaherCellID = @"wheatherCellId";
static NSString *cycleCellID = @"cycleCellID";
static NSString *functonCellID = @"functionCellID";
static NSString *mingYiCellID = @"mingyi";

@interface HomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,WGWheathCollectionViewCellDelegate>

@property(nonatomic,weak) UICollectionView *collectionView  ;
/**轮播图片*/
@property(nonatomic,strong)NSArray<WGCycleImageModel *> *images;

/**功能数据*/
@property(nonatomic,strong)NSArray<HMHomeFunctionModel *> *funtionList;

/**天气数据*/
@property(nonatomic,strong)NSArray<Weather *> *wheatherList;

/**城市数据*/
@property(nonatomic,strong)NSArray<WGCityModel *> *cityList;

/**城市**/

@property(nonatomic,copy)NSString *city;

/**疾病数据*/
@property(nonatomic,strong)NSArray<Disease *> *diseaseList;

/**并发症数据*/
@property(nonatomic,strong)NSArray<WGComplicationModel *> *complicationList;


/**遮罩视图*/
@property(nonatomic,weak)UIView *coverView;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置自动布局
    [Adapter adapt:self];
    
    self.view.backgroundColor = [UIColor redColor];
    
    //加载在天气数据
    //加载城市数据
    self.city = @"上海";
    [self loadWheatherDataWithCity:self.city];
    
    //加载数据
    [self loadCycleImages];
    
    //加载城市数据
    [self loadCityData];
    
    
    //搭建UI界面
    [self setupUI];
    
}
#pragma
#pragma mark - 加载城市数据
-(void)loadCityData{
    
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"province.plist" ofType:nil];
    NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
    
    self.cityList = [NSArray yy_modelArrayWithClass:[WGCityModel class] json:array];
    
}

#pragma
#pragma mark - 获取天气数据
-(void)loadWheatherDataWithCity:(NSString *)city{
    
    [[NetWorkManager sharedManager] loadWheatherWithCurrentCity:city Completed:^(NSArray<Weather *> *wheatherList) {
        
        self.wheatherList = wheatherList;
        [self.collectionView reloadData];
        
    }];
    
}


#pragma
#pragma mark - 加载功能数据
-(NSArray<HMHomeFunctionModel *> *)funtionList{
    
    if (_funtionList == nil) {
        
        _funtionList = [HMHomeFunctionModel loadHomeFunction];
    }
    
    return _funtionList;
}

#pragma
#pragma mark - 加载轮播器数据
-(void)loadCycleImages{
    
    NSArray *imagesArray = @[
                             @"http://img.guahao.com/portal_upload/rollingnews/1453447883150.jpg",
                             @"http://img.guahao.com/portal_upload/mediafocus/1461826474435.jpg",
                             @"http://img.guahao.com/portal_upload/rollingnews/1461574027543.jpg"
                             ];
    self.images = imagesArray;
}


#pragma
#pragma mark -  搭建UI界面

- (void)setupUI {
    
    self.title = @"首页";
    
    self.navigationController.navigationBar.barTintColor = kThemeColor;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:SCREEN_BOUNDS collectionViewLayout:layout];
    self.collectionView = collectionView;
    [self.view addSubview:collectionView];
    
    //设置数据源,代理
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    
    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:testCellId];
    
    //注册cell
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"WGWheathCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:wheaherCellID];
    
    [self.collectionView registerClass:[WGCycleCollectionViewCell class] forCellWithReuseIdentifier:cycleCellID];
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"WGMingYiCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:mingYiCellID];
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"ZWHomeFunctionCell" bundle:nil] forCellWithReuseIdentifier:functonCellID];
    
    //设置背景颜色
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    //关闭弹簧
    
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.bounces = NO;
    
    //设置增加按钮
    UIButton *rightItem = [UIButton buttonWithType:0];
    rightItem.bounds = CGRectMake(0, 0, 30, 30);
    UIImage *image = [[UIImage imageNamed:@"home_scan"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [rightItem setBackgroundImage:image forState:UIControlStateNormal];
    
    [rightItem addTarget:self action:@selector(addScan) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIBarButtonItem *Item = [[UIBarButtonItem alloc]initWithCustomView:rightItem];
    self.navigationItem.rightBarButtonItem = Item;
    
    [self setNavigationBar];
    
}

#pragma
#pragma mark - 设置导航栏
-(void)setNavigationBar{
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor] }];
}


#pragma
#pragma mark - 添加导航
-(void)addScan{
  

    WGScanViewController *scanVc = [[WGScanViewController alloc ]init];;
    
    
//    UIViewController *vc = [[UIViewController alloc]init];
    
    [self.navigationController pushViewController:scanVc animated:YES];
    
}

#pragma mark - dataSource delegate

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 4;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    switch (section) {
        case 0:
            return 1;
        case 1:
            return 1;
        case 2:
            return 1;
        case 3:
            return self.funtionList.count ;
            
        default:
            return 0;
            break;
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        WGWheathCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:wheaherCellID forIndexPath:indexPath];
        
        Weather *model = self.wheatherList[0];
        cell.model = model;
        [cell.btn_city setTitle:self.city forState:UIControlStateNormal];
        
        
        //设置代理属性
        cell.delegate = self;
        
        return cell;
    }else if(indexPath.section == 1){
        WGCycleCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:cycleCellID forIndexPath:indexPath];
        if (self.images!=nil) {
            cell.images = self.images;
        }
        
        return cell;
        
    } else if(indexPath.section == 2){
        
        WGMingYiCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:mingYiCellID forIndexPath:indexPath];
        return cell;
        
        
    }else if(indexPath.section == 3){
        
        ZWHomeFunctionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:functonCellID forIndexPath:indexPath];
        
        HMHomeFunctionModel *model = self.funtionList[indexPath.row];
        
        cell.model = model;
        
        return cell;
        
    }else{
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:testCellId forIndexPath:indexPath];
        cell.backgroundColor = [UIColor jq_randomColor];
        return cell;
    }
}

#pragma
#pragma mark - 返回各个cell的size

#define kWeatherH 100
#define KCycleH 200
#define kMingYiH 50

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    switch (indexPath.section) {
        case 0:
            return CGSizeMake(SCREEN_WIDTH, kWeatherH);
            break;
        case 1:
            return CGSizeMake(SCREEN_WIDTH, KCycleH);
            break;
        case 2:
            return CGSizeMake(SCREEN_WIDTH, kMingYiH);
        case 3:
            return CGSizeMake((SCREEN_WIDTH - 3)/ 4, (SCREEN_HEIGHT -kWeatherH - KCycleH - kMingYiH - 80 ) / 2);
             break;
            
    }
    return CGSizeZero;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 2) {
        
        //跳转到心跳测试
        
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"WGTestHeartRateViewController" bundle:nil];
        WGTestHeartRateViewController *vc = [sb instantiateInitialViewController];
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    
    
    if (indexPath.section == 3 && indexPath.item < 5)
    {
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"WGDesease" bundle:nil];
        
        WGDeseaseController *deseaseVc = [sb instantiateViewControllerWithIdentifier:@"diseaseID"];
        //取出model
        HMHomeFunctionModel *model = self.funtionList[indexPath.row];
        
        NSLog(@"model = %zd",model.ci1_id);
        
        deseaseVc.model = model;
        
#pragma mark - 判断用户是否登录
        BOOL islogin =  [MLDefaults boolForKey:kIsUserLoginKey];
        if (islogin) {
            //如果登录,push到下一个界面
            [self.navigationController pushViewController:deseaseVc animated:YES];
        }else{
            
            //如果没登录,弹出提示框,需要用户注册账号,或登录
            NSLog(@"对不起,你需要登录");
            
            [self noLogin];
        }
    }
    
    
    if (indexPath.section == 3 && indexPath.item == 5) {
        
        BJXieHeViewController *gongYiVc = [[BJXieHeViewController alloc]init];
        [self.navigationController pushViewController:gongYiVc animated:YES];
        
    }
    
}

#pragma
#pragma mark - 没有登录的逻辑

-(void)noLogin{
    
#pragma
#pragma mark - 出现遮罩
    
    UIView *coverView = [[UIView alloc]initWithFrame:SCREEN_BOUNDS];
    self.coverView = coverView;
    coverView.alpha = 0;
    coverView.backgroundColor = [UIColor blackColor];
    [[UIApplication sharedApplication].keyWindow addSubview:coverView];
    
#pragma
#pragma mark - 出现提示框
    __block WGALertLoginView *loginView = [WGALertLoginView alertLoginView];
    
    [self.coverView addSubview:loginView];
    
#define kLoginViewW 260
#define kLoginViewH 160
    
    loginView.bounds = CGRectMake(0, 0, kLoginViewW , kLoginViewH );
    loginView.center = self.coverView.center;
    
    [UIView animateWithDuration:2 animations:^{
        coverView.alpha = 0.8;
        
    }];
    
    
#pragma mark - 实现立即登录
    loginView.AlertLoginBlock = ^{
        [UIView animateWithDuration:1 animations:^{
            coverView.alpha = 0;
        }completion:^(BOOL finished) {
            
            [coverView removeFromSuperview];
        }];
    };
}



#pragma
#pragma mark - <WGWheathCollectionViewCellDelegate>
-(void)clickCityButtonWithWheathCollectionViewCell:(WGWheathCollectionViewCell *)cell{
    
    WGCityTableViewController *vc = [[WGCityTableViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    vc.cityList = self.cityList;
    
}


#pragma
#pragma mark - 完成城市天气的切换
//视图将要显示
-(void)viewWillAppear:(BOOL)animated{
    
    //接受通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveCityNotication:) name: kSelectedeCityNotiCation object:nil];
    
}

#pragma
#pragma mark - 接受城市通知
-(void)receiveCityNotication:(NSNotification *)noti{
    
    self.city = noti.object;
    //重新加载城市数据
    [self loadWheatherDataWithCity:self.city];
    [self.collectionView reloadData];
}

-(void)viewDidAppear:(BOOL)animated{
    //重新加载城市数据
    [self loadWheatherDataWithCity:self.city];
    
    [self.collectionView reloadData];
    
}
@end
